package com.voxel.sense.infomsg.module.firm.details.history;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.utils.constants.TimeConstants;
import com.example.com.common.widget.diffui.DiffUiDataCallBack;
import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.base.RecyclerViewPresenter;
import com.voxel.sense.infomsg.data.bean.ElementInfoBean;
import com.voxel.sense.infomsg.data.bean.HistoryDataListBean;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.data.bean.RealDataBean;
import com.voxel.sense.infomsg.widget.SourceCharDiffUtilsCallBack;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.HistoryDataEntity;
import cyy.example.com.facotry.net.helper.FirmNetHelper;

/**
 * Created by ChenYiYao on 2018/8/1.
 */
public class HistoryPresenter extends RecyclerViewPresenter<HistoryDataContract.View> implements HistoryDataContract.Presenter, DataSource.Callback<BaseEntity<HistoryDataEntity>> {
    private Handler mHandler;
    final private static int DATA_REFRESH = 200;
    final private static int NOT_DATA = 400;
    private List<MultiItemBean> mList;
    private String mId;
    private String mStartTime;
    private String mEndTime;

    public HistoryPresenter(HistoryDataContract.View view) {
        super(view);
    }

    @Override
    public void start() {
        super.start();
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (mView == null)
                    return false;
                List data = (List) msg.obj;
                DiffUiDataCallBack callback = new SourceCharDiffUtilsCallBack();
                loadDataComplete(data, callback);
                return false;
            }
        });
        setRefreshWay(WayConstants.DIFF);
        mList = new ArrayList();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    protected void loadData() {
        FirmNetHelper.getFirmHistoryData(getPAGE_NUMB() + "", getPageDataSize()+ "", "2", mStartTime, mEndTime, "", mId, HistoryPresenter.this);
    }

    @Override
    protected void loadMoreData() {
        FirmNetHelper.getFirmHistoryData(getPAGE_NUMB()+ "", getPageDataSize()+ "", "2", mStartTime, mEndTime, "", mId, HistoryPresenter.this);
    }

    @Override
    public void doLoadMore() {
        startLoadMoreData();
        //该接口目前是加载全部，所有没有加载更多
//        mView.onLoadMoreFinish();
    }

    @Override
    public void doRefresh(String id, String startTime, String endTime) {
        this.mId = id;

        if (TextUtils.isEmpty(startTime) && TextUtils.isEmpty(endTime)) {
            mStartTime = "";
            mEndTime = "";
            startRefreshData();
            return;
        }

        //转成时间戳
        long milStart = TimeUtils.string2Millis(startTime, new SimpleDateFormat(Constants.TimeYMDHFormat));
        long milEnd = TimeUtils.string2Millis(endTime, new SimpleDateFormat(Constants.TimeYMDHFormat));

        if (TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.pleas_pick_start_time));
            mView.onRefreshFinish();
        } else if (!TextUtils.isEmpty(startTime) && TextUtils.isEmpty(endTime)) {
            ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.pleas_pick_end_time));
            mView.onRefreshFinish();
        } else if (milStart > milEnd) {
            ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.start_cannot_more_than_end));
            mView.onRefreshFinish();
        } else {

            //将时间转为服务器接收的格式
            mStartTime = TimeUtils.millis2String(milStart, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE));
            //由于选择的时间都是整点的，结束时间应该是下一个整点之前的59分59秒
            mEndTime = TimeUtils.millis2String(milEnd + TimeConstants.HOUR - TimeConstants.SEC, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE));
            startRefreshData();
        }
    }


    @Override
    public void onDataLoaded(final BaseEntity<HistoryDataEntity> data, int reqId) {
        if (mView == null)
            return;


        if (data.isSuccess() && data.getData() != null) {
            //每个元素最新的数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mHandler.removeCallbacksAndMessages(null);
                    //分别构造超标数据，表格数据，图标数据类型的数据
                    Message message = mHandler.obtainMessage();
                    List<MultiItemBean> reaData = createReaData(data.getData());
                    message.obj = reaData;
                    message.sendToTarget();
                }
            }).start();
        } else {
            mView.onRefreshFinish();
            mView.onLoadMoreFinish();
        }

    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }
        LoadDataFailure();
        if (NetworkUtils.isConnected()) {
            mView.showEmptyView(Factory.app().getString(R.string.data_rsp_error_unknown), true);
        } else {
            mView.showEmptyView(Factory.app().getString(R.string.data_rsp_error), true);
        }
    }


    /**
     * 构造图表实时数据实体
     */
    private List<MultiItemBean> createReaData(HistoryDataEntity data) {
        List<MultiItemBean> list = new ArrayList();
        HistoryDataEntity.SiteStandValueVoBean siteStandValueVo = data.getSiteStandValueVo();
        List<Map<String, String>> analysisVoList = data.getAnalysisVoList();

        //组装元素
        if (siteStandValueVo != null && siteStandValueVo.getParamThirftObjectList() != null &&
                siteStandValueVo.getParamThirftObjectList().size() > 0 && analysisVoList != null && analysisVoList.size() > 0) {
            Map<String, ElementInfoBean> mapDatas = new HashMap<>();
            //单独取出每个元素信息
            for (HistoryDataEntity.SiteStandValueVoBean.ParamThirftObjectListBean bean : siteStandValueVo.getParamThirftObjectList()) {
                //从站位信息中，获取所有的元素信息，以便提取单位等信息
                ElementInfoBean realBean = new ElementInfoBean();
                realBean.setParamName(bean.getParamName());
                realBean.setParamUnit(bean.getParamUnit());
                realBean.setStandarValues(bean.getParamValue());
                realBean.setParamDubValue(bean.getParamDubValue());
                //将元素封装进map当中
                mapDatas.put("p" + bean.getParamCode(), realBean);
            }

            for (Map<String, String> valueMap : analysisVoList) {
                Set<String> keySet = valueMap.keySet();

                Iterator<String> iterator = keySet.iterator();

                //采集时间
                String time = valueMap.get("_id");

                long millis = 0L;
                if(!TextUtils.isEmpty(time)) {
                     millis = TimeUtils.getMillis(time, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE), 0, TimeConstants.SEC);
                }

                //封装通一个时间点采集的数据
                List<RealDataBean> dataListBeans = new ArrayList<>();
                for (String key : keySet) {
                    if ("_id".equals(key))//跳过时间项
                        continue;
                    //封装相同时间点的数据到一个集合中
                    ElementInfoBean siteItemBean = mapDatas.get(key);
                    if (siteItemBean != null) {
                        //提取值
                        String value = valueMap.get(key);
                        RealDataBean tableBean = new RealDataBean(siteItemBean.getParamUnit(), siteItemBean.getParamName(),
                                millis, value, siteItemBean.getStandarValues());
                        dataListBeans.add(tableBean);
                    }

                }
                if (dataListBeans.size() > 0) {
                    HistoryDataListBean<List<RealDataBean>> historyData = new HistoryDataListBean<>(millis, dataListBeans);
                    MultiItemBean<HistoryDataListBean> tableItem =
                            new MultiItemBean(historyData, Constants.NORMAL_TYPE);
                    //表格数据
                    list.add(tableItem);
                }
            }
        }
        return list;
    }

}
